<template>
  <div class="system-roles">
    <div class="page-header">
      <h1 class="page-title">预约列表</h1>
    </div>

    <div v-if="!isDoctor" class="placeholder-content">
      <el-empty description="仅医生账号可查看聊天预约列表" />
    </div>

    <div v-else class="chat-list" v-loading="loading">
      <div class="chat-list-header">
        <span>聊天预约列表</span>
        <el-button size="small" type="primary" text @click="refresh">刷新</el-button>
      </div>

      <div v-if="items.length === 0" class="placeholder-content">
        <el-empty description="暂无会话" />
      </div>

      <div v-else class="chat-items">
        <div
          v-for="it in items"
          :key="it._id"
          class="chat-item"
          :class="{ 'has-unread': it.count > 0 }"
          @click="openChat(it)"
        >
          <img class="avatar" :src="it.avatar" @error="onAvatarError($event, it)" />
          <div class="content">
            <div class="row top">
              <div class="name">{{ it.username }}</div>
              <div class="time">{{ formatTime(it.lastTime) }}</div>
            </div>
            <div class="row bottom">
              <div class="last-text" :class="lastTextClass(it.lastText)">{{ displayLastText(it.lastText) }}</div>
              <el-badge v-if="it.count > 0" :value="it.count" type="danger" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()

const isDoctor = computed(() => userStore.userInfo?.roles?.some(r => r.code === 'doctor'))
const loading = ref(false)

interface ChatListItem {
  _id: string
  username: string
  avatar: string
  count: number
  lastTime: number
  lastText: string
}

const items = ref<ChatListItem[]>([])

const API_BASE = (import.meta as any).env?.VITE_API_BASE_URL || 'http://localhost:3000'

function formatTime(ts: number) {
  if (!ts) return ''
  const d = new Date(ts)
  const now = new Date()
  const sameDay = d.toDateString() === now.toDateString()
  if (sameDay) return d.toTimeString().slice(0, 5)
  const diff = now.getTime() - ts
  const oneDay = 24 * 60 * 60 * 1000
  if (diff < 7 * oneDay) {
    const w = ['日','一','二','三','四','五','六']
    return `周${w[d.getDay()]}`
  }
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
}

function displayLastText(text: string) {
  if (text === '[图片]') return '[图片]'
  if (text === '[语音消息]') return '[语音]'
  return text || ''
}

function lastTextClass(text: string) {
  if (text === '[图片]') return 'image-message'
  if (text === '[语音消息]') return 'voice-message'
  return ''
}

function onAvatarError(e: Event, it: ChatListItem) {
  const target = e.target as HTMLImageElement
  target.src = `https://picsum.photos/80/80?random=${it._id}`
}

async function fetchJSON(url: string): Promise<any> {
  const res = await fetch(url)
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
  return res.json()
}

async function getDoctorVirtualId(): Promise<string | null> {
  // 依据登录用户名匹配医生姓名，返回虚拟用户ID：doctor_<doctorId>
  const username = userStore.userInfo?.username || ''
  if (!username) return null
  try {
    const data = await fetchJSON(`${API_BASE}/cosmetic/doctors?limit=1000`)
    // 响应可能是 { success, data } 或数组
    const doctors = Array.isArray(data) ? data : (Array.isArray(data?.data) ? data.data : [])
    const doc = doctors.find((d: any) => d?.name === username)
    if (doc && doc._id) return `doctor_${doc._id}`
    return null
  } catch (e) {
    return null
  }
}

async function loadList() {
  if (!isDoctor.value) return
  loading.value = true
  try {
    const currentUserId = await getDoctorVirtualId()
    if (!currentUserId) {
      items.value = []
      ElMessage.warning('未在医生列表中找到与用户名匹配的医生')
      return
    }

    const [unreadRaw, chatsRaw] = await Promise.all([
      fetchJSON(`${API_BASE}/messages/unreadSummary?userId=${encodeURIComponent(currentUserId)}`),
      fetchJSON(`${API_BASE}/chats?userId=${encodeURIComponent(currentUserId)}`)
    ])

    // 兼容未读返回对象或数组
    const unreadMap: Record<string, { count: number, lastTime: number }> = Array.isArray(unreadRaw)
      ? (unreadRaw as any[]).reduce((acc, it: any) => {
          const id = String(it.userId || it.peerId || it._id || '')
          if (id) acc[id] = { count: Number(it.count || 0), lastTime: Number(it.lastTime || 0) }
          return acc
        }, {} as Record<string, { count: number, lastTime: number }>)
      : (unreadRaw || {})

    const chats = Array.isArray(chatsRaw) ? chatsRaw : (Array.isArray(chatsRaw?.list) ? chatsRaw.list : [])

    const peerToLastTime: Record<string, number> = {}
    const peerToLastText: Record<string, string> = {}
    const peers: Set<string> = new Set()

    chats.forEach((c: any) => {
      const participants: any[] = c?.participants || []
      const other = participants.find((p: any) => String(p?._id || p) !== String(currentUserId))
      const otherId = String(other?._id || other || '')
      if (!otherId) return
      peers.add(otherId)
      const last = (c.messages || []).slice(-1)[0]
      const t = last ? new Date(last.createdAt).getTime() : 0
      peerToLastTime[otherId] = Math.max(peerToLastTime[otherId] || 0, t)
      if (last) peerToLastText[otherId] = last.content
    })

    const peerIds = Array.from(peers)
    let usersArr: any[] = []
    if (peerIds.length) {
      try {
        const usersRes = await fetchJSON(`${API_BASE}/users/byIds?ids=${encodeURIComponent(peerIds.join(','))}`)
        usersArr = Array.isArray(usersRes) ? usersRes : (Array.isArray(usersRes?.list) ? usersRes.list : (Array.isArray(usersRes?.items) ? usersRes.items : Object.values(usersRes || {})))
      } catch (_) {}
    }

    const userMap: Record<string, any> = {}
    usersArr.forEach((u: any) => { if (u && u._id) userMap[String(u._id)] = u })

    const list = Array.from(new Set([ ...Object.keys(unreadMap), ...Object.keys(peerToLastTime) ])).map((id) => {
      const u = userMap[id] || {}
      const displayName = u.nickname || u.username || u.name || `用户${id.slice(-4)}`
      const displayAvatar = u.avatar || u.avatarUrl || `https://picsum.photos/80/80?random=${id}`
      return {
        _id: id,
        username: displayName,
        avatar: displayAvatar,
        count: unreadMap[id]?.count || 0,
        lastTime: Math.max(unreadMap[id]?.lastTime || 0, peerToLastTime[id] || 0),
        lastText: peerToLastText[id] || ''
      }
    }).sort((a, b) => {
      const aUnread = a.count > 0 ? 1 : 0
      const bUnread = b.count > 0 ? 1 : 0
      if (aUnread !== bUnread) return bUnread - aUnread
      return (b.lastTime || 0) - (a.lastTime || 0)
    })

    items.value = list
  } catch (e: any) {
    ElMessage.error(`加载会话失败：${e?.message || '未知错误'}`)
  } finally {
    loading.value = false
  }
}

function refresh() {
  loadList()
}

function openChat(it: ChatListItem) {
  router.push({ name: 'AppointmentCalendar', query: { peerId: it._id, peerName: it.username } })
}

onMounted(() => {
  loadList()
})
</script>

<style lang="scss" scoped>
.system-roles {
  .page-header {
    margin-bottom: 24px;

    .page-title {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }
  }

  .placeholder-content {
    background: white;
    border-radius: 8px;
    padding: 60px;
    text-align: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    height: 100vh;
  }

  .chat-list {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .chat-list-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;
      font-weight: 600;
      color: #333;
    }

    .chat-items {
      display: flex;
      flex-direction: column;
      gap: 12px;

      .chat-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px;
        border: 1px solid #eee;
        border-radius: 8px;

        &.has-unread {
          background: #fff8f8;
        }

        .avatar {
          width: 48px;
          height: 48px;
          border-radius: 50%;
          object-fit: cover;
        }

        .content {
          flex: 1;
          min-width: 0;

          .row {
            display: flex;
            align-items: center;
            justify-content: space-between;

            &.top {
              .name {
                font-weight: 600;
                color: #333;
                max-width: 70%;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
              }

              .time {
                color: #999;
                font-size: 12px;
              }
            }

            &.bottom {
              margin-top: 6px;

              .last-text {
                color: #666;
                font-size: 13px;
                max-width: 80%;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;

                &.image-message {
                  color: #409eff;
                }
                &.voice-message {
                  color: #67c23a;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>